package yang.itcode.interceptor;

import cn.hutool.json.JSONUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import yang.itcode.model.Result;
import yang.itcode.utils.JwtUtil;
import yang.itcode.utils.ThreadUtil;

import static yang.itcode.constant.JwtConstant.JWT_ID;
import static yang.itcode.constant.JwtConstant.JWT_SECRET;

@Component
@Slf4j
public class UserJwtInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1、从请求头中获取令牌
        String token = request.getHeader("Authorization");
        if(token == null || !token.startsWith("Bearer ")){
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(401);
            return false;
        }
        token = token.substring(7); // 去掉 "Bearer " 前缀

        //2、校验令牌
        try {
            log.info("jwt校验:{}", token);
            Claims claims = JwtUtil.parseJWT(JWT_SECRET, token);
            Integer userId = Integer.valueOf(claims.get(JWT_ID).toString());
            log.info("当前用户的id：{}", userId);
            ThreadUtil.setCurrentId(userId);
            //3、通过，放行
            return true;
        } catch (ExpiredJwtException ex) {
            //4、令牌过期，响应401状态码和提示信息
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(401);
            response.getWriter().write(JSONUtil.toJsonStr(Result.error(300,"令牌过期")));
            return false;
        } catch (Exception ex) {
            //5、其他异常，响应401状态码
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(401);
            response.getWriter().write(JSONUtil.toJsonStr(Result.error(300,"无效的令牌")));
            return false;
        }
    }
}
